window.onload = function () {
  var container = document.querySelector("#container");
  var canvas = document.createElement("canvas");
  canvas.width = container.clientWidth;
  canvas.height = container.clientHeight;
  container.appendChild(canvas);

  window.onresize = function () {
    canvas.width = container.clientWidth;
    canvas.height = container.clientHeight;
  };

  var gl = canvas.getContext("webgl");

  var VERTEX_SHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'attribute vec4 a_Color;\n' +
    'uniform mat4 u_ViewMatrix;\n' +
    'varying vec4 v_Color;\n' +
    'void main(){\n' +
    'gl_Position = u_ViewMatrix * a_Position;\n' +
    'v_Color = a_Color;\n' +
    '}\n';

  var FRAGMENT_SHADER_SOURCE =
    'precision mediump float;\n' + // float变量没有默认精度，所以使用前必须声明，否则会出错
    'varying vec4 v_Color;\n' +
    'void main(){\n' +
    'gl_FragColor = v_Color;\n' +
    '}';


  // 1.1创建着色器对象
  var vertex_shader_object = gl.createShader(gl.VERTEX_SHADER);
  var fragment_shader_object = gl.createShader(gl.FRAGMENT_SHADER);

  // 1.2装载着色器资源
  gl.shaderSource(vertex_shader_object, VERTEX_SHADER_SOURCE);
  gl.shaderSource(fragment_shader_object, FRAGMENT_SHADER_SOURCE);

  // 1.3编译着色器
  gl.compileShader(vertex_shader_object);
  gl.compileShader(fragment_shader_object);

  // 2.1创建程序
  var program = gl.createProgram();

  // 2.2.附着着色器对象到program
  gl.attachShader(program, vertex_shader_object);
  gl.attachShader(program, fragment_shader_object);

  // 2.3.链接program
  gl.linkProgram(program);

  // 2.4.使用program
  gl.useProgram(program);



  var u_ViewMatrix = gl.getUniformLocation(program, 'u_ViewMatrix')
  var viewMatrix = new Matrix4()
  viewMatrix.setLookAt(0.25, 0.25, 0.25, 0, 0, 0, 0, 1, 0)
  // viewMatrix.setLookAt(0.25, 0.25, 0.25, 0, 0, 0, -0.25, 0.75, -0.25) // 视线和上方向可以不垂直么
  // 将视图矩阵传递给u_ViewMatrix
  gl.uniformMatrix4fv(u_ViewMatrix, false, viewMatrix.elements)

  var vertices_Positions_Colors = new Float32Array([
    0.0, 0.5, 1.0, 0.0, 0.0,
    -0.5, -0.5, 0.0, 1.0, 1.0,
    0.5, -0.5, 0.0, 0.0, 1.0,
  ]);
  var a_Position = gl.getAttribLocation(program, "a_Position");
  var a_Color = gl.getAttribLocation(program, "a_Color");
  var fsize = vertices_Positions_Colors.BYTES_PER_ELEMENT;

  // 处理位置
  var vertex_Positon_Buffer = gl.createBuffer(gl.ARRAY_BUFFER);
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_Positon_Buffer);
  gl.bufferData(gl.ARRAY_BUFFER, vertices_Positions_Colors, gl.STATIC_DRAW);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, fsize * 5, 0);
  gl.enableVertexAttribArray(a_Position);

  // 处理颜色
  var vertex_Color_Buffer = gl.createBuffer(gl.ARRAY_BUFFER);
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_Color_Buffer);
  gl.bufferData(gl.ARRAY_BUFFER, vertices_Positions_Colors, gl.STATIC_DRAW);
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, fsize * 5, fsize * 2);
  gl.enableVertexAttribArray(a_Color);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
}

